package kim.artemis.rpc.core.loadbalance;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 负载均衡轮询策略
 * @author Wq.
 */
@Slf4j
public class ArtemisRpcLoadBalancePolling extends ArtemisRpcLoadBalance {

    private ConcurrentHashMap<String, Integer> routeCountEachRequest = new ConcurrentHashMap<String, Integer>();
    private long CACHE_VALID_TIME = 0;

    private int count (String serviceKey) {
        // 清空计数
        if(CACHE_VALID_TIME < System.currentTimeMillis()) {
            routeCountEachRequest.clear();
            CACHE_VALID_TIME = System.currentTimeMillis() + 24 * 60 * 60 * 1000;
        }
        Integer count = routeCountEachRequest.get(serviceKey);
        // 初始化时候主动随机一次
        count = (null == count || 100000 < count) ? (new Random().nextInt(100)) : ++count;
        routeCountEachRequest.put(serviceKey, count);
        return count;
    }

    @Override
    public String route (String serviceKey, TreeSet<String> addressSet) {
        String[] socketAddressArr = addressSet.toArray(new String[addressSet.size()]);
        return socketAddressArr[count(serviceKey) % socketAddressArr.length];
    }
}
